﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BPM.Entity;
using BPM.Common;
using Webdiyer.WebControls.Mvc;

namespace BPM.Service
{
    public class MaterialDefinitionService : ServiceBase<MaterialDefinition>
    {
        public PagedList<MaterialDefinition> Search(string companyName, string materialName, int pageIndex, int pageSize)
        {
            var q = this.Query().Where(m => m.IsApproved);
            if (!string.IsNullOrWhiteSpace(companyName))
            {
                q = q.Where(m => m.SupplierName.Contains(companyName));
            }
            if (!string.IsNullOrWhiteSpace(materialName))
            {
                q = q.Where(m => m.Name.Contains(materialName));
            }
            q = q.OrderByDescending(m => m.Id);
            var res = q.ToPagedList(pageIndex, pageSize);
            return EnableLazyLoading(res);
        }

        public PagedList<MaterialDefinition> GetPending(int pageIndex, int pageSize)
        {
            var result = this.Query().Where(m => m.IsApproved == false).OrderBy(m => m.Id).ToPagedList(pageIndex, pageSize);
            return EnableLazyLoading(result);
        }

        public MaterialDefinition GetByBarcode(string barcode)
        {
            return this.Query().FirstOrDefault(m => m.Barcode.Number == barcode);
        }

        protected override Result Create(MaterialDefinition entity)
        {
            return Create(entity, null);
        }

        public Result Create(MaterialDefinition entity, string barcodeNumber = null)
        {
            //Barcode
            var barcodeSvc = new BarcodeService();
            Barcode barcode = null;
            var res = barcodeSvc.New(SysBarcodeCategories.MaterialDefinition, out barcode);
            if (!res) return res;

            if (!string.IsNullOrWhiteSpace(barcodeNumber))
            {
                barcode.Number = barcodeNumber;
            }
            res = barcodeSvc.Save(barcode);
            if (!res) return res;

            entity.BarcodeId = barcode.Id;

            entity.IsApproved = false;

            return base.Create(entity);
        }

        public override Result Delete(int id)
        {
            return this.Delete(id, null, u =>
            {
                return new BarcodeService().Delete(u.BarcodeId);
            });
        }

        public Result ApproveMaterial(int id)
        {
            MaterialDefinition def = this.GetById(id);
            def.IsApproved = true;
            return this.Update(def);
        }
    }
}
